﻿using Newtonsoft.Json;
using QWManage.Utils;
using System.Collections.Generic;

namespace QWManage.API.DepartmentList95350
{
    /// <summary>
    /// 获取子部门ID列表
    /// </summary>
    internal class DepartmentListAPI
    {
        /*
         *  请求方式：GET（HTTPS）
            请求地址：https://qyapi.weixin.qq.com/cgi-bin/department/simplelist?access_token=ACCESS_TOKEN&id=ID

        参数	必须	说明
access_token	是	调用接口凭证
id	否	部门id。获取指定部门及其下的子部门（以及子部门的子部门等等，递归）。 如果不填，默认获取全量组织架构
         */

        public static List<int> Invoke(string token, string id = null)
        {
            List<int> ids = new List<int>();
            string url = $"https://qyapi.weixin.qq.com/cgi-bin/department/simplelist?access_token={token}";
            if (!string.IsNullOrEmpty(id)) url += "&id=" + id;

            string result = HttpHelper.GetHtmlSource(url);
            var root = JsonConvert.DeserializeObject<Root>(result);
            foreach (Department_id depart in root.department_id)
            {
                if (!ids.Contains(depart.id)) ids.Add(depart.id);

            }
            return ids;
        }
    }

    #region JSON
    public class Department_id
    {
        /// <summary>
        /// 
        /// </summary>
        public int id { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int parentid { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int order { get; set; }
    }

    public class Root
    {
        /// <summary>
        /// 
        /// </summary>
        public int errcode { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string errmsg { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public List<Department_id> department_id { get; set; }
    }

    #endregion
}
